//   Copyright 2012,2013 Vaughn Vernon
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
package com.saasovation.identityaccess.infrastructure.persistence;

import com.saasovation.identityaccess.domain.model.identity.Group;
import com.saasovation.identityaccess.domain.model.identity.GroupRepository;
import com.saasovation.identityaccess.domain.model.identity.TenantId;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.exception.ConstraintViolationException;
import org.hibernate.query.Query;

import java.util.Collection;

public class HibernateGroupRepository implements GroupRepository {
    private final SessionFactory sessionFactory;

    public HibernateGroupRepository(SessionFactory sessionFactory) {
        super();
        this.sessionFactory = sessionFactory;
    }

    @Override
    public void add(Group aGroup) {
        try {
            this.getCurrentSession().persist(aGroup);
        } catch (ConstraintViolationException e) {
            throw new IllegalStateException("Group is not unique.", e);
        }
    }

    @Override
    public Collection<Group> allGroups(TenantId aTenantId) {
        Query<Group> query = this.getCurrentSession().createQuery(
                "from com.saasovation.identityaccess.domain.model.identity.Group as _obj_ "
                        + "where _obj_.tenantId = :tenantId "
                        + "and _obj_.name not like '" + Group.ROLE_GROUP_PREFIX + "%'",
                Group.class);
        query.setParameter("tenantId", aTenantId);
        return query.list();
    }

    @Override
    public Group groupNamed(TenantId aTenantId, String aName) {
        if (aName.startsWith(Group.ROLE_GROUP_PREFIX)) {
            throw new IllegalArgumentException("May not find internal groups.");
        }
        Query<Group> query = this.getCurrentSession().createQuery(
                "from com.saasovation.identityaccess.domain.model.identity.Group as _obj_ "
                        + "where _obj_.tenantId = :tenantId "
                        + "and _obj_.name = :name", Group.class);
        query.setParameter("tenantId", aTenantId);
        query.setParameter("name", aName);
        return query.uniqueResult();
    }

    @Override
    public void remove(Group aGroup) {
        this.getCurrentSession().remove(aGroup);
    }

    private Session getCurrentSession() {
        return this.sessionFactory.getCurrentSession();
    }
}
